package com.example.demo15.interceptor;

import com.example.demo15.entity.User;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 * 登录拦截器，用于控制未登录用户访问受保护资源
 */
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");

        if (user == null) {
            // 使用 URLEncoder 对中文进行编码
            String encodedMsg = URLEncoder.encode("请先登录", StandardCharsets.UTF_8.toString());
            try {
                response.sendRedirect("/login?msg=" + encodedMsg);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return false;
        }

        return true;
    }
}
